package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"gitee.com/liu_deping/gin-vue/common"
	"gitee.com/liu_deping/gin-vue/db"
	"gitee.com/liu_deping/gin-vue/model"
	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {

	return func(ctx *gin.Context) {
		//1.获取authorrization header
		tokenString := ctx.GetHeader("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不够",
			})
			ctx.Abort()
			return
		}
		//2.验证tokenString
		tokenString = tokenString[7:]
		token, claims, err := common.ParesToken(tokenString)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不够",
			})
			ctx.Abort()
			return
		}
		fmt.Println(token)
		//3.获取claims中的userID,确认用户是否存在
		userID := claims.UserId
		var user model.User
		db.DB.First(&user, userID)
		if user.ID == 0 {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不够",
			})
			ctx.Abort()
			return
		}
		//4. 用户存在，将user的信息写入gin.Context
		ctx.Set("user", user)
		ctx.Next()
	}
}
